// 路由的相关配置，得到路由实例。
import Vue from 'vue'
import VueRouter from 'vue-router'
// 工具模块
import auth from '@/utils/auth'

// 导入组件(路由懒加载)
const Login = () => import('@/views/login')
const Layout = () => import('@/views/Layout')
const Welcome = () => import('@/views/welcome')
const Article = () => import('@/views/article')
const Image = () => import('@/views/image')
const Publish = () => import('@/views/publish')
const Comment = () => import('@/views/comment')
const Fans = () => import('@/views/fans')
const Setting = () => import('@/views/setting')
const NotFound = () => import('@/views/404')

Vue.use(VueRouter)

// 路由规则
const routes = [
  // 登录
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    children: [
      // 欢迎
      { path: '/', component: Welcome },
      // 内容
      { path: '/article', component: Article },
      // 素材
      { path: '/image', component: Image },
      // 发布
      { path: '/publish', component: Publish },
      // 评论
      { path: '/comment', component: Comment },
      // 粉丝
      { path: '/fans', component: Fans },
      // 个人设置
      { path: '/setting', component: Setting }
    ]
  },
  // 以上规则都没有匹配，使用一个通配规则，指向一个404组件即可
  { path: '*', component: NotFound }
]

// 路由实例
const router = new VueRouter({ routes })

// 导航守卫
router.beforeEach((to, from, next) => {
  // 解构得到获取用信息的函数
  const { getUser } = auth
  // 除去登录外，其他页面需要判断token是否存在，如果不存储拦截到登录
  if (to.path !== '/login' && !getUser().token) return next('/login')
  // 其他情况一律放行
  next()
})

// 导出实例
export default router
